import 'dart:async';

import 'package:get/get.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:path/path.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/services/storage.dart';
import 'package:sainbainu/common/values/settings.dart';
import 'package:sainbainu/common/values/storage_keys.dart';

class JpushService extends GetxService {
  static JpushService get to => Get.find();

  late JPush _jpush;

  @override
  void onInit() {
    super.onInit();
    init();
  }

  init() {
    _jpush = JPush();
    _jpush.addEventHandler(
      onReceiveNotification: _onReceiveNotification,
      onOpenNotification: _onOpenNotification,
      onReceiveMessage: _onReceiveMessage,
      onConnected: _onConnected,
      onInAppMessageShow: _onInAppMessageShow,
      onInAppMessageClick: _onInAppMessageClick,
      onNotifyMessageUnShow: _onNotifyMessageUnShow,
      onReceiveNotificationAuthorization: _onReceiveNotificationAuthorization,
    );
    _jpush.setup(
      appKey: AppSettings.jPushAppKey,
      channel: 'developer-default',
      production: false,
      debug: AppSettings.isDebug,
    );
  }

  /// 申请推送权限（隐私弹窗后调用）
  applyPushAuthority() {
    _jpush.applyPushAuthority(
      const NotificationSettingsIOS(sound: true, alert: true, badge: true),
    );
  }

  /// 获取设备注册ID（登录时调用）
  Future<String?> getRegistrationID() async {
    var registrationId = StorageService.to.getString(
      StorageKeys.jpushRegistrationId,
    );
    if (registrationId == null) {
      try {
        registrationId = await _jpush.getRegistrationID();
        StorageService.to.setString(
          StorageKeys.jpushRegistrationId,
          registrationId,
        );
      } catch (e) {
        // 获取失败不影响流程 所以不让错误冒泡了
      }
    }
    return registrationId;
  }

  /// 设置应用小红点（获取未读消息后调用）
  setBadge(int badge) async {
    var res = await _jpush.setBadge(badge);
    _print("setBadge $res");
  }

  /// 调用此 API 检测通知授权状态是否打开
  Future<bool> isNotificationEnabled() async {
    return await _jpush.isNotificationEnabled();
  }

  /// 调用此 API 跳转至系统设置中应用设置界面
  void openSettingsForNotification() {
    _jpush.openSettingsForNotification();
  }

  /// 发送本地通知到调度器，指定时间出发该通知
  Future<String> sendLocalNotification(LocalNotification notification) async {
    return await _jpush.sendLocalNotification(notification);
  }

  /// 接收通知回调
  Future _onReceiveNotification(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter onReceiveNotification: $message");

    // 跳转指定页面
    if (message['page'] != null) {
      Get.toNamed(message['page']);
    }
    // 跳转网页
    else if (message['jpush_pri_rich_url'] != null) {
      Get.toNamed(AppRoutes.webview, arguments: {
        'url': message['jpush_pri_rich_url'],
        'title': '自定义页面标题',
      });
    }
  }

  /// 点击通知回调
  Future _onOpenNotification(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter onOpenNotification: $message");
  }

  /// 接收自定义消息回调
  Future _onReceiveMessage(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter onReceiveMessage: $message");
  }

  Future _onConnected(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter onConnected: $message");
  }

  Future _onInAppMessageShow(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter _onInAppMessageShow: $message");
  }

  Future _onInAppMessageClick(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter _onInAppMessageClick: $message");
  }

  Future _onNotifyMessageUnShow(Map<String, dynamic> message) async {
    _print("📢📢📢📢📢📢📢flutter _onNotifyMessageUnShow: $message");
  }

  Future _onReceiveNotificationAuthorization(
      Map<String, dynamic> message) async {
    _print(
        "📢📢📢📢📢📢📢flutter _onReceiveNotificationAuthorization: $message");
  }

  /// 打印
  _print(String message) {
    print('📢📢📢📢📢📢📢 $message');
  }
}
